package controller

import (
	"context"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"user_bff/pkg"
	"user_bff/user_proto"
)

func UserLogin(c *gin.Context) {
	mobile := c.PostForm("mobile")
	password := c.PostForm("password")
	if mobile == "" || password == "" {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "参数不能为空",
			"data": nil,
		})
		return
	}
	comment := pkg.Comment()
	byMobile, err := comment.GetUserByMobile(context.Background(), &user_proto.GetUserByMobileRequest{Mobile: mobile})
	if err != nil {
		_, err := comment.UserRegister(context.Background(), &user_proto.UserRegisterRequest{
			Mobile:   mobile,
			Password: pkg.Md5(password),
		})
		if err != nil {
			zap.S().Panic(err)
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "用户注册成功,请重新登录",
			"data": nil,
		})
		return
	}
	if pkg.Md5(password) != byMobile.Password {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "密码错误",
			"data": nil,
		})
		return
	}
	token, err := pkg.SetJwtToken(strconv.FormatInt(byMobile.Id, 10))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "token生成失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "用户登录成功",
		"data": token,
	})
}
